//
//  SLPermissionSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/25.
//

#import "SLAccessSettingVC.h"
#import "SLAccessSettingView.h"
#import "SLUnlockAlertView.h"
#import "SLLockLogVC.h"
#import "SLSetAccessNameVC.h"
#import "SLShareAlertView.h"
#import "SCSxTimeRangePickView.h"
#import "SLDaySelectAlertView.h"

@interface SLAccessSettingVC ()<DatePickerViewDelegate>{
    UIView *_dateBgView;
    
    NSString *_dateFormart;
    NSString *_timeFormart;
    NSString *_submitFormart;
    BOOL _isFirstLoad;
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLAccessSettingView *headView;
@property (nonatomic, strong)SCSxTimeRangePickView *timeRangePickView;
@property (nonatomic, strong)SLDaySelectAlertView *daySelectView;
@property (nonatomic, strong)NSArray *selectDays;
@property (nonatomic, strong)SLLockKeyModel *tempKeyModel;
@end

@implementation SLAccessSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFingerDatas) name:@"kRefreshAccessSettingVc" object:nil];
    [self setUpSubViews];
    if (_keyModel.lockType == 1) {
        [ZCTool showLoadingOnKeyWindow];
        [self loadFingerDatas];
    }else{
        [self refreshSubViews];
        if (_isAddBlueToothKey) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ZCTool showShareAlertView:self->_keyModel.keyId];
            });
        }
    }
    _tempKeyModel = [SLLockKeyModel modelWithDictionary:[_keyModel modelToJSONObject]];
}

-(void)backBtnClicked{
    [super backBtnClicked];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)loadFingerDatas{
    kWeakSelf(self);
    NSDictionary *params = @{@"keyId":_keyModel.keyId,
                             @"uid":_keyModel.uid,
                             @"page":@"1",
                             @"pageSize":@"999"};
    [ZKHttpManager getWithPath:@"/msl_lock_key/LockFing/list" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        
        NSArray *data = [[NSArray alloc] initWithArray:result[@"result"][@"items"]];
        //更新数据源
        NSMutableArray *fingers = [NSMutableArray new];
        [data enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockFingerModel *model = [SLLockFingerModel modelWithDictionary:dict];
            [fingers addObject:model];
        }];
        weakself.keyModel.fingers = fingers;
        [weakself refreshSubViews];
    }];
}

-(void)refreshSubViews{
    [self updateSelectDays];
    [self updateHeight];
    [self.headView refreshWith:self.keyModel];
}

-(void)setUpSubViews{
    self.title = _keyModel.keyName;
    _dateFormart = @"MMM. d, yyyy";
    _timeFormart = @"MMM. d, yyyy  HH:mm";
    _submitFormart = @"yyyy-MM-dd";
    [self addNavigationItemWithImageNames:@[@"icon_delete"] isLeft:NO target:self action:@selector(deleteAction) tags:@[@"1000"]];
    
    [self.view addSubview:self.tableView];
    //永久钥匙没有save按钮
    if (_keyModel.keyType != 1) {
        ZKBaseButton *sureBtn = [ZKBaseButton buttonWithType:UIButtonTypeCustom];
        sureBtn.frame = CGRectMake(20, kScreenHeight-SafeAreaBottomHeight-70, kScreenWidth-40, 50);
        sureBtn.btnStyle = 1;
        sureBtn.font = kFontBold(16);
        [sureBtn setTitle:kLocalString(@"Save and sync") forState:UIControlStateNormal];
        [self.view addSubview:sureBtn];
        [sureBtn addTarget:self action:@selector(sysAction) forControlEvents:UIControlEventTouchUpInside];
    }else{
        _tableView.frame = CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight);
    }
    
    _headView = [SLAccessSettingView viewFromXIB];
    _headView.frame = self.tableView.bounds;
    kWeakSelf(self);
    [_headView setBtnBlock:^(NSInteger index) {
        [weakself handleSetView:index];
    }];
    [_headView setListBlock:^(NSInteger btnIndex) {
        [weakself handleListAction:btnIndex];
    }];
    [_headView setSwitchBlock:^(NSInteger isOpen) {
        [weakself switchSettingWith:isOpen];
    }];
    [self updateHeight];
    _tableView.tableHeaderView = _headView;
}

-(void)switchSettingWith:(NSInteger)isOpen{
    [self sysKeyDatasWith:NO];
}

-(void)updateHeight{
    CGFloat height = self.tableView.height;
    CGFloat defaultHeight = 500;
    CGFloat fingerHeight = 0;
    if (_keyModel.keyType == 2) {
        defaultHeight += 200;
    }else if (_keyModel.keyType == 3){
        defaultHeight += 100;
    }
    if (_keyModel.lockType == 1) {
        defaultHeight -= 70;
        fingerHeight = _keyModel.fingers.count * 50;
    }
    
    height = MAX(height, defaultHeight+fingerHeight);
    
    self.headView.height = height;
    self.tableView.tableHeaderView = _headView;
    [_tableView layoutIfNeeded];
}

#pragma mark -
#pragma mark - ================<删除钥匙>===============
-(void)deleteAction{
    kWeakSelf(self);
    [SLTipAlertView showWith:kLocalString(@"Make sure you want to delete this access?") content1:kLocalString(@"You can reclaim this access again by visiting the access link you received.") content2:@"" doneBtn:kLocalString(@"Delete") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 0) {
            return;
        }
        if (self->_keyModel.lockType == 2) {
            [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Deleting...")];
            NSString *url = [NSString stringWithFormat:@"/msl_lock_key/delete/%@",self->_keyModel.keyId];
            [ZKHttpManager deleteWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [weakself deleteFinish:isSuccessed];
            }];
            return;
        }
        //先连接设备
        [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Deleting...")];
        [ZCTool connectDeviceWith:kCurClickDevice toast:@"" finish:^(BOOL isSuccess) {
            if (!isSuccess) {
                [ZCTool hideLoadingOnKeyWindow];
                return;
            }
            //连接上了，先服务端删除
            NSString *url = [NSString stringWithFormat:@"/msl_lock_key/delete/%@",self->_keyModel.keyId];
            [ZKHttpManager deleteWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                if (!isSuccessed) {
                    [ZCTool hideLoadingOnKeyWindow];
                    kShowToast(message);
                    return;
                }
                //服务端删除了之后再硬件端删除
                [[SLBluetoothManager sharedManager] deleteUserFingerAccessWith:self->_keyModel.uid accessId:@"" finish:^(NSString *commond, BOOL isDeleteSuccess, id data, NSString *errorMsg) {
                    [weakself deleteFinish:isDeleteSuccess];
                }];
            }];
        }];
    }];
}

-(void)deleteFinish:(BOOL)isSuccessed{
    //硬件删除失败
    if (!isSuccessed) {
        [ZCTool hideLoadingOnKeyWindow];
        kShowToast(@"Delete faild");
        return;
    }
    //硬件端删除成功
    kShowToast(@"Delete success!");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshKeyData" object:@{}];
        kNotifyRefreshDevcieList;
    });
}

#pragma mark -
#pragma mark - ================<保存修改>===============
//修改开锁方式保存
-(void)sysAction{
    [self sysKeyDatasWith:YES];
}

-(void)sysKeyDatasWith:(BOOL)isShowToast{
    //蓝牙锁
    if (_keyModel.lockType == 2) {
        [self updateTempKyeModel];
        [ZCTool showLoadingOnKeyWindow];
        [self uploadKeyData:isShowToast];
        return;
    }
    
    //指纹锁
    [ZCTool showLoadingOnKeyWindow];
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        
        if (!isSuccess) {
            self->_headView.changeBtn.on = [self->_keyModel.status isEqualToString:@"0"];
            [ZCTool hideLoadingOnKeyWindow];
            return;
        }
        
        [self updateTempKyeModel];
        //修改开锁方式
        [[SLBluetoothManager sharedManager] editFingerAccessWith:self->_tempKeyModel isManager:YES finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
            if (!isSuccess) {
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(errorMsg);
                return;
            }
             //设备设置成功 - 同步给服务器
            [self uploadKeyData:isShowToast];
        }];
    }];
}

-(void)updateTempKyeModel{
    _tempKeyModel.status = _headView.changeBtn.isOn ? @"0":@"1";
    NSString *startDateStr = [self submitDateStrWith:_headView.listContentLbl2.text];
    NSString *endDateStr = [self submitDateStrWith:_headView.listContentLbl3.text];
    if (_keyModel.keyType == 2) {
        //更新提交的值
        if (_headView.timeChangeBtn.isOn) {//有循环
            _tempKeyModel.weekDays = [self getWeekDaysValue];
        }else{//没循环
            _tempKeyModel.weekDays = @[];
        }
        NSString *time1 = [_headView.startTimeLbl.text copy];
        NSString *time2 = [_headView.endTimeLbl.text copy];
        _tempKeyModel.startTime = [NSString stringWithFormat:@"%@ %@:00",startDateStr,time1];
        _tempKeyModel.endTime = [NSString stringWithFormat:@"%@ %@:00",endDateStr,time2];
        _tempKeyModel.dayStart = time1;
        _tempKeyModel.dayEnd = time2;
    }else if(_keyModel.keyType == 3){//一次性钥匙
        _tempKeyModel.startTime = startDateStr;
        _tempKeyModel.endTime = endDateStr;
    }
}

-(void)uploadKeyData:(BOOL)isShowToast{
    
    //设备设置成功 - 同步给服务器
    [ZKHttpManager sysncKeyDataWith:_tempKeyModel finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        [self updateKeyModel];
        //修改成功
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (isShowToast) kShowToast(@"Save and sync success");
        });
        [self refreshSubViews];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshKeyData" object:@{}];
    }];
}

-(NSString *)submitDateStrWith:(NSString *)dateStr{
    NSString *formart = _keyModel.keyType == 3 ?_timeFormart : _dateFormart;
    NSString *submitFormart = _keyModel.keyType == 3 ? @"yyyy-MM-dd HH:mm:ss" : @"yyyy-MM-dd";
    NSDate *date = [NSDate dateFromDateStr:dateStr formatStr:formart];
    NSString *sumbitDateStr = [NSString dateStrFromDate:date formatStr:submitFormart];
    return sumbitDateStr;
}


-(void)updateKeyModel{
    _keyModel.dayEnd = _tempKeyModel.dayEnd;
    _keyModel.dayStart = _tempKeyModel.dayStart;
    _keyModel.startTime = _tempKeyModel.startTime;
    _keyModel.endTime = _tempKeyModel.endTime;
    _keyModel.weekDays = _tempKeyModel.weekDays;
    _keyModel.status = _tempKeyModel.status;
}

-(void)handleSetView:(NSInteger )index{
    if (index == 1) {//编辑
        [self showInputView];
    }else if (index == 2){//添加
        SLSetAccessNameVC *vc = [[SLSetAccessNameVC alloc] init];
        SLLockFingerModel *model = [SLLockFingerModel new];
        model.uid = _keyModel.uid;
        model.keyId = _keyModel.keyId;
        vc.fingerModel = model;
        vc.isAddFinger = YES;
        vc.keyModel = _keyModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//范围时间钥匙修改
-(void)handleListAction:(NSInteger)index{
    if (index == 1) {//开始日期
        [self showDateViewWith:1];
    }else if (index == 2) {//开始时间
        [self showDateViewWith:2];
    }else if (index == 3){//结束日期
        [self showDateViewWith:3];
    }else if (index == 4){//结束时间
        [self showDateViewWith:4];
    }else if (index == 5){//选择周几
        [self showDaySelectView];
    }else if (index == 6){//分享
        [ZCTool showShareAlertView:_keyModel.keyId];
    }else if (index == 7){//切换repeat
        if (_headView.timeChangeBtn.isOn) {
            if (_tempKeyModel.weekDays == nil || _tempKeyModel.weekDays.count == 0) {
                _selectDays = @[kLocalString(@"Monday"),kLocalString(@"Tuesday"),kLocalString(@"Wednesday"),kLocalString(@"Thursday"),kLocalString(@"Friday"),kLocalString(@"Saturday"),kLocalString(@"Sunday")];
                _tempKeyModel.weekDays = [self getWeekDaysValue];
            }
        }else{
            _tempKeyModel.weekDays = @[];
        }
        _headView.listContentLbl4.text = [self dayStr];
    }
}

-(void)showDateViewWith:(NSInteger)tag{
    CGSize size = [[UIScreen mainScreen] bounds].size;
    _dateBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    _dateBgView.backgroundColor = [kHexColor(@"#0C0C0C") colorWithAlphaComponent:0.8];
    [[[UIApplication sharedApplication] keyWindow] addSubview:_dateBgView];
    DatePickerView *datePickerView = [[DatePickerView alloc] initWithFrame:CGRectMake(0, KScreenHeight - 250, KScreenWidth, 250)];
    datePickerView.layer.cornerRadius = 10;
    datePickerView.layer.masksToBounds = YES;
    datePickerView.fundelegate = self;
    if (_keyModel.keyType == 2) {
        if (tag == 2 || tag == 4) {
            datePickerView.datePickerMode = UIDatePickerModeTime;
        }else{
            datePickerView.datePickerMode = UIDatePickerModeDate;
        }
    }else{
        datePickerView.datePickerMode = UIDatePickerModeDateAndTime;
    }
    datePickerView.tag = tag;
    NSDate *now = [NSDate date];
    [datePickerView.datePicker setDate:now animated:YES];
    datePickerView.datePicker.frame = CGRectMake(0, 50, KScreenWidth, 200);
    [[[UIApplication sharedApplication] keyWindow] addSubview:datePickerView];
}

-(void)didDatePickerViewDoneClicked:(DatePickerView *)aPickerView{
    NSInteger tag = aPickerView.tag;
    NSDate *selectDate = [aPickerView selectDate];
    //时间段钥匙
    if (_keyModel.keyType == 2) {
        if (tag == 1) {//开始日期
            _headView.listContentLbl2.text = [selectDate stringWithFormat:_dateFormart];
        }else if(aPickerView.tag == 2){//开始时间
            _headView.startTimeLbl.text = [selectDate stringWithFormat:@"HH:mm"];
        }else if(aPickerView.tag == 3){//结束日期
            _headView.listContentLbl3.text = [selectDate stringWithFormat:_dateFormart];
        }else if(aPickerView.tag == 4){//结束时间
            _headView.endTimeLbl.text = [selectDate stringWithFormat:@"HH:mm"];
        }
    }
    //一次性钥匙
    else{
        if (tag == 1) {//开始时间
            _headView.listContentLbl2.text = [selectDate stringWithFormat:_timeFormart];
        }else if(aPickerView.tag == 3){//结束时间
            _headView.listContentLbl3.text = [selectDate stringWithFormat:_timeFormart];
        }
    }
    [_dateBgView removeFromSuperview];
    [aPickerView removeFromSuperview];
}


- (void)didDatePickerViewCancelClicked:(DatePickerView*)aPickerView{
    [_dateBgView removeFromSuperview];
    [aPickerView removeFromSuperview];
}

-(void)updateSelectDays{
    NSMutableArray *arr = [NSMutableArray new];
    if (_selectDays == nil) {
        [_keyModel.weekDays enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isEqualToString:@"0"]) {
                [arr addObject:kLocalString(@"Sunday")];
            }else if ([obj isEqualToString:@"1"]){
                [arr addObject:kLocalString(@"Monday")];
            }else if ([obj isEqualToString:@"2"]){
                [arr addObject:kLocalString(@"Tuesday")];
            }else if ([obj isEqualToString:@"3"]){
                [arr addObject:kLocalString(@"Wednesday")];
            }else if ([obj isEqualToString:@"4"]){
                [arr addObject:kLocalString(@"Thursday")];
            }else if ([obj isEqualToString:@"5"]){
                [arr addObject:kLocalString(@"Friday")];
            }else if ([obj isEqualToString:@"6"]){
                [arr addObject:kLocalString(@"Saturday")];
            }
        }];
        _selectDays = arr;
    }
}

-(NSArray *)getWeekDaysValue{
    if (_selectDays == nil || _selectDays.count == 0) {
        return @[@"1",@"2",@"3",@"4",@"5",@"6",@"0"];
    }
    NSMutableArray *arr = [NSMutableArray new];
    [_selectDays enumerateObjectsUsingBlock:^(NSString *dayStr, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([dayStr isEqualToString:kLocalString(@"Monday")]) {
            [arr addObject:@"1"];
        }else if ([dayStr isEqualToString:kLocalString(@"Tuesday")]){
            [arr addObject:@"2"];
        }else if ([dayStr isEqualToString:kLocalString(@"Wednesday")]){
            [arr addObject:@"3"];
        }else if ([dayStr isEqualToString:kLocalString(@"Thursday")]){
            [arr addObject:@"4"];
        }else if ([dayStr isEqualToString:kLocalString(@"Friday")]){
            [arr addObject:@"5"];
        }else if ([dayStr isEqualToString:kLocalString(@"Saturday")]){
            [arr addObject:@"6"];
        }else if ([dayStr isEqualToString:kLocalString(@"Sunday")]){
            [arr addObject:@"0"];
        }
    }];
    return arr;
}

-(void)showDaySelectView{
    if (_daySelectView) {
        return;
    }
    _daySelectView = [SLDaySelectAlertView viewFromXIB];
    [self.view addSubview:_daySelectView];
    
    [_daySelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _daySelectView.selects = (NSMutableArray *)_selectDays;
    kWeakSelf(self);
    [_daySelectView setBtnBlock:^(NSArray * _Nonnull selects,NSInteger index) {
        [weakself.daySelectView removeFromSuperview];
        weakself.daySelectView = nil;
        if (index == 1) {
            weakself.selectDays = selects;
            weakself.headView.listContentLbl4.text = [weakself dayStr];
        }
    }];
}

-(NSString *)dayStr{
    if (_selectDays.count == 7) {
        return kLocalString(@"Every day");
    }else{
        NSString *dayStr = [_selectDays componentsJoinedByString:@"./"];
        return dayStr;
    }
}

-(void)showInputView{
    __weak SLInputAlertView *alert = [SLInputAlertView viewFromXIB];
    alert.titleLbl.text = kLocalString(@"Edit Name");
    [alert.tf setPlaceholderWithPlaceholderText:kLocalString(@"Enter access name") withColor:KColor_placeholdar withFont:kFont(16)];
    [alert setBtnBlock:^(NSString *text, NSInteger btnIndex) {
        if (btnIndex == 2) {
            [alert removeFromSuperview];
            return;
        }
        if (btnIndex == 1) {
            if (text.length == 0) {
                kShowToast(@"Enter access name");
                return;
            }
            [alert removeFromSuperview];
            
            NSDictionary *params = @{@"keyId":self->_keyModel.keyId,
                                     @"keyName":text,
                                     @"deviceId":kCurClickDevice.deviceId};
            [ZCTool showLoadingOnKeyWindow];
            [ZKHttpManager postWithPath:@"/msl_lock_key/updateKey" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                [ZCTool hideLoadingOnKeyWindow];
                if (!isSuccessed) {
                    kShowToast(message);
                    return;
                }
                self->_keyModel.keyName = text;
                self->_tempKeyModel.keyName = text;
                self.title = text;
                self->_headView.topContentLbl1.text = text;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshKeyData" object:@{}];
            }];
        }
    }];
    [kAppWindow addSubview:alert];
}

-(void)handleShareViewAction:(NSInteger )index{
    SLShareAlertView *alertView = [self.view viewWithTag:100];
    [alertView removeFromSuperview];
    if (index == 1) {//去分享
        NSString *str = [NSString stringWithFormat:@"%@ %@",kLocalString(@"You have received HEXFORCE Bluetooth Key from"),kUserInfo.nickName];
        [ZCTool shareWithTitle:str httpUrl:alertView.linkLbl.text vc:self];
    }else if (index == 2){//跳过
        
    }
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-70-15) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}


@end
